package service

import (
	"errors"
	"fmt"
	"github.com/cn-ygf/go-admin/internal/modular/system/dao"
	"github.com/cn-ygf/go-admin/internal/modular/system/model"
	"github.com/cn-ygf/go-admin/internal/modular/system/vo"
)

var (
	RoleService = new(roleService)
)

var (
	RoleNameUniqueError = errors.New("角色名已存在")
	RoleKeyUniqueError  = errors.New("权限字符已存在")
	SuperRoleError      = errors.New("不允许操作超级管理员角色")
)

// roleService 角色管理
type roleService struct {
}

func (s roleService) GetList() ([]*model.SysRole, error) {
	return dao.SysRole.Where(dao.SysRole.Status.Eq("0")).Find()
}

// QueryList 分页查询角色列表
func (s roleService) QueryList(req *vo.QueryRoleListReq) ([]*model.SysRole, int64, error) {
	var (
		r = dao.SysRole
		d = r.Where()
	)
	if req.PageSize < 1 {
		req.PageSize = 10
	}
	if req.PageNum < 1 {
		req.PageNum = 1
	}
	if req.RoleName != "" {
		d = d.Where(r.RoleName.Like("%" + req.RoleName + "%"))
	}
	if req.RoleKey != "" {
		d = d.Where(r.RoleKey.Eq(req.RoleKey))
	}
	if req.Status != "" {
		d = d.Where(r.Status.Eq(req.Status))
	}
	if req.Params != nil {
		if req.Params.BeginTime > 0 && req.Params.EndTime > 0 {
			d = d.Where(r.CreatedAt.Gte(req.Params.BeginTime))
			d = d.Where(r.CreatedAt.Lte(req.Params.EndTime))
		}
	}
	return d.FindByPage((req.PageNum-1)*req.PageSize, req.PageSize)
}

// GetByID 根据userId查询用户
func (s roleService) GetByID(roleId int64) (*model.SysRole, error) {
	return dao.SysRole.Where(dao.SysRole.RoleID.Eq(roleId)).First()
}

// ChangeStatus 修改用户状态
func (s roleService) ChangeStatus(roleId int64, status string) error {
	_, err := dao.SysRole.Where(dao.SysRole.RoleID.Eq(roleId)).Update(dao.SysRole.Status, status)
	return err
}

// GetPermIdsByRoleId // 获取角色关联的权限菜单
func (s roleService) GetPermIdsByRoleId(roleId int64) []int64 {
	r := make([]int64, 0)
	rms, err := dao.SysRoleMenu.Where(dao.SysRoleMenu.RoleID.Eq(roleId)).Find()
	if err != nil {
		systemLog.Errorln(err.Error())
		return r
	}
	for _, item := range rms {
		r = append(r, item.MenuID)
	}
	return r
}

// Add 添加角色
func (s roleService) Add(req *vo.AddRoleReq) error {
	if !s.CheckRoleNameUnique(0, req.RoleName) {
		return UserNameUniqueError
	}
	if !s.CheckRoleKeyUnique(0, req.RoleKey) {
		return RoleKeyUniqueError
	}
	u := dao.SysRole
	newRole := &model.SysRole{
		RoleName:          req.RoleName,
		RoleKey:           req.RoleKey,
		RoleSort:          req.RoleSort,
		DataScope:         "1",
		MenuCheckStrictly: req.MenuCheckStrictly,
		DeptCheckStrictly: true,
		Status:            req.Status,
		CreateBy:          req.CreateBy,
		UpdateBy:          "",
		Remark:            req.Remark,
	}
	err := u.Create(newRole)
	if err != nil {
		systemLog.Errorln(err.Error())
		return ServerError
	}
	if req.MenuIds != nil {
		menuLen := len(req.MenuIds)
		if menuLen > 0 {
			rms := make([]*model.SysRoleMenu, menuLen)
			for index, item := range req.MenuIds {
				rms[index] = &model.SysRoleMenu{
					RoleID: newRole.RoleID,
					MenuID: item,
				}
			}
			err = dao.SysRoleMenu.CreateInBatches(rms, menuLen)
			if err != nil {
				systemLog.Errorln(err.Error())
				return ServerError
			}
		}
	}
	return nil
}

// Update 修改角色
func (s roleService) Update(req *vo.EditRoleReq) error {
	if !s.CheckRoleNameUnique(req.RoleId, req.RoleName) {
		return RoleNameUniqueError
	}
	if !s.CheckRoleKeyUnique(req.RoleId, req.RoleKey) {
		return RoleKeyUniqueError
	}
	u := dao.SysRole
	_, err := u.Where(u.RoleID.Eq(req.RoleId)).Updates(map[string]any{
		u.RoleName.ColumnName().String():                    req.RoleName,
		u.RoleKey.ColumnName().String():                     req.RoleKey,
		u.RoleSort.ColumnName().String():                    req.RoleSort,
		u.Status.ColumnName().String():                      req.Status,
		u.Remark.ColumnName().String():                      req.Remark,
		u.UpdateBy.ColumnName().String():                    req.UpdateBy,
		dao.SysRole.MenuCheckStrictly.ColumnName().String(): req.MenuCheckStrictly,
	})
	if err != nil {
		systemLog.Errorln(err.Error())
		return ServerError
	}
	_, err = dao.SysRoleMenu.Where(dao.SysRoleMenu.RoleID.Eq(req.RoleId)).Delete()
	if err != nil {
		systemLog.Errorln(err.Error())
		return ServerError
	}
	if req.MenuIds != nil {
		menuLen := len(req.MenuIds)
		if menuLen > 0 {
			rms := make([]*model.SysRoleMenu, menuLen)
			for index, item := range req.MenuIds {
				rms[index] = &model.SysRoleMenu{
					RoleID: req.RoleId,
					MenuID: item,
				}
			}
			err = dao.SysRoleMenu.CreateInBatches(rms, menuLen)
			if err != nil {
				systemLog.Errorln(err.Error())
				return ServerError
			}
		}
	}
	return err
}

// Delete 删除角色
func (s roleService) Delete(roleIds []int64) error {
	for _, roleId := range roleIds {
		if roleId == 1 {
			return SuperRoleError
		}
		count, err := s.CountUserRoleByRoleId(roleId)
		if err != nil {
			systemLog.Errorln(err.Error())
			return ServerError
		}
		if count > 0 {
			role, _ := s.GetByID(roleId)
			return fmt.Errorf("%s已分配,不能删除", role.RoleName)
		}
	}
	// 删除角色与菜单关联
	err := s.DeleteRoleMenu(roleIds)
	if err != nil {
		systemLog.Errorln(err.Error())
		return ServerError
	}
	// 删除角色与部门关联
	err = s.DeleteRoleDept(roleIds)
	if err != nil {
		systemLog.Errorln(err.Error())
		return ServerError
	}

	// 删除角色
	_, err = dao.SysRole.Where(dao.SysRole.RoleID.In(roleIds...)).Delete()
	return err
}

// DeleteRoleMenu 删除角色与权限菜单的关系
func (s roleService) DeleteRoleMenu(roleIds []int64) error {
	_, err := dao.SysRoleMenu.Where(dao.SysRoleMenu.RoleID.In(roleIds...)).Delete()
	return err
}

// DeleteRoleDept 删除角色与部门的关系
func (s roleService) DeleteRoleDept(roleIds []int64) error {
	_, err := dao.SysRoleDept.Where(dao.SysRoleDept.RoleID.In(roleIds...)).Delete()
	return err
}

// CountUserRoleByRoleId 通过角色ID查询角色使用数量
func (s roleService) CountUserRoleByRoleId(roleId int64) (int64, error) {
	return dao.SysUserRole.Where(dao.SysUserRole.RoleID.Eq(roleId)).Count()
}

// CheckRoleNameUnique 检查角色名称是否已存在
func (s roleService) CheckRoleNameUnique(roleId int64, roleName string) bool {
	if roleId == 0 {
		count, err := dao.SysRole.Where(dao.SysRole.RoleName.Eq(roleName)).Count()
		if err != nil {
			systemLog.Errorln(err.Error())
			return true
		}
		return count < 1
	}
	role, err := s.GetByID(roleId)
	if err != nil {
		systemLog.Errorln(err.Error())
		return true
	}
	if role.RoleName == roleName {
		return true
	}
	count, err := dao.SysRole.Where(dao.SysRole.RoleName.Eq(roleName)).Count()
	if err != nil {
		systemLog.Errorln(err.Error())
		return true
	}
	return count < 1
}

// CheckRoleKeyUnique 检查权限字符串是否已存在
func (s roleService) CheckRoleKeyUnique(roleId int64, roleKey string) bool {
	if roleId == 0 {
		count, err := dao.SysRole.Where(dao.SysRole.RoleKey.Eq(roleKey)).Count()
		if err != nil {
			systemLog.Errorln(err.Error())
			return true
		}
		return count < 1
	}
	role, err := s.GetByID(roleId)
	if err != nil {
		systemLog.Errorln(err.Error())
		return true
	}
	if role.RoleKey == roleKey {
		return true
	}
	count, err := dao.SysRole.Where(dao.SysRole.RoleKey.Eq(roleKey)).Count()
	if err != nil {
		systemLog.Errorln(err.Error())
		return true
	}
	return count < 1
}

// DataScope 分配角色数据范围
func (s roleService) DataScope(req *vo.DataScopeReq) error {
	_, err := dao.SysRoleDept.Where(dao.SysRoleDept.RoleID.Eq(req.RoleId)).Delete()
	if err != nil {
		systemLog.Errorln(err.Error())
		return ServerError
	}
	_, err = dao.SysRole.Where(dao.SysRole.RoleID.Eq(req.RoleId)).Updates(map[string]any{
		dao.SysRole.DataScope.ColumnName().String():         req.DataScope,
		dao.SysRole.DeptCheckStrictly.ColumnName().String(): req.DeptCheckStrictly,
	})
	if err != nil {
		systemLog.Errorln(err.Error())
		return ServerError
	}
	if req.DeptIds != nil {
		deptIdsLen := len(req.DeptIds)
		if deptIdsLen > 0 {
			depts := make([]*model.SysRoleDept, deptIdsLen)
			for i, deptId := range req.DeptIds {
				depts[i] = &model.SysRoleDept{
					RoleID: req.RoleId,
					DeptID: deptId,
				}
			}
			err = dao.SysRoleDept.CreateInBatches(depts, deptIdsLen)
			if err != nil {
				systemLog.Errorln(err.Error())
				return ServerError
			}
		}
	}
	return nil
}

// AllocatedList 查询角色
func (s roleService) AllocatedList(req *vo.AllocatedListReq) ([]*model.SysUser, int64, error) {
	var (
		u = dao.SysUser
		d = u.Where()
	)
	if req.PageSize < 1 {
		req.PageSize = 10
	}
	if req.PageNum < 1 {
		req.PageNum = 1
	}
	if req.UserName != "" {
		d = d.Where(u.UserName.Like("%" + req.UserName + "%"))
	}

	if req.Phonenumber != "" {
		d = d.Where(u.Phonenumber.Eq(req.Phonenumber))
	}
	var userIds []int64
	err := dao.SysUserRole.Select(dao.SysUserRole.UserID).Where(dao.SysUserRole.RoleID.Eq(req.RoleId)).Scan(&userIds)
	if err != nil {
		systemLog.Errorln(err.Error())
		return nil, 0, ServerError
	}

	d = d.Where(u.UserID.In(userIds...))
	return d.FindByPage((req.PageNum-1)*req.PageSize, req.PageSize)
}

// UnallocatedList 查询无关联的用户
func (s roleService) UnallocatedList(req *vo.AllocatedListReq) ([]*model.SysUser, int64, error) {
	var (
		u = dao.SysUser
		d = u.Where()
	)
	if req.PageSize < 1 {
		req.PageSize = 10
	}
	if req.PageNum < 1 {
		req.PageNum = 1
	}
	if req.UserName != "" {
		d = d.Where(u.UserName.Like("%" + req.UserName + "%"))
	}

	if req.Phonenumber != "" {
		d = d.Where(u.Phonenumber.Eq(req.Phonenumber))
	}
	var userIds []int64
	err := dao.SysUserRole.Select(dao.SysUserRole.UserID).Where(dao.SysUserRole.RoleID.Eq(req.RoleId)).Scan(&userIds)
	if err != nil {
		systemLog.Errorln(err.Error())
		return nil, 0, ServerError
	}

	d = d.Where(u.UserID.NotIn(userIds...))
	return d.FindByPage((req.PageNum-1)*req.PageSize, req.PageSize)
}

// BindUser 角色绑定用户
func (s roleService) BindUser(roleId int64, userIds []int64) error {
	userLen := len(userIds)
	if userLen > 0 {
		userList := make([]*model.SysUserRole, userLen)
		for index, item := range userIds {
			userList[index] = &model.SysUserRole{
				UserID: item,
				RoleID: roleId,
			}
		}
		return dao.SysUserRole.CreateInBatches(userList, userLen)
	}

	return nil
}

// UnbindUser 权限授权
func (s roleService) UnbindUser(roleId int64, userId int64) error {
	_, err := dao.SysUserRole.Where(dao.SysUserRole.RoleID.Eq(roleId)).Where(dao.SysUserRole.UserID.Eq(userId)).Delete()
	return err
}
